<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
        0.1.第一种: 特权方法
     */
    function MyObject() {
        // 私有变量和私有函数
        let privateVariable = 10;

        function privateFunction() {
            return false;
        }

        // 特权方法
        this.publicMethod = function () {
            privateVariable++;
            return privateFunction();
        };
    }

    let obj = new MyObject();
    obj.publicMethod();  // 只能访问publicMethod

    /*
        0.2.第二种: 
            - 缺点: 每个实例都会重新创建一遍新方法
     */

    function Person(name) {
        this.getName = function () {
            return name;
        };
        this.setName = function (value) {
            name = value
        }
    }

    let person = new Person('Nicholas');
    console.log(person.getName());


    /*
        1. 静态私有变量
     */
    (function () {
        // 私有变量和私有函数
        let privateVariable = 10;

        function privateFunction() {
            return false;
        }

        // 构造函数
        MyObject = function () {
        };
        // 公有和特权方法 
        MyObject.prototype.publicMethod = function () {
            privateVariable++;
            return privateFunction();
        };
    })();
    let obj2 = new MyObject();
    console.log(obj2.publicMethod());

    /*
        1.2 第二种
     */

    (function () {
        let name = '';
        Person = function (value) {
            name = value;
        };
        Person.prototype.getName = function () {
            return name;
        };
        Person.prototype.setName = function (value) {
            name = value;
        };
    })();
    let person1 = new Person('Nicholas');
    console.log(person1.getName()); // 'Nicholas' 
    person1.setName('Matt');
    console.log(person1.getName()); // 'Matt'
    let person2 = new Person('Michael');
    console.log(person1.getName()); // 'Michael' 
    console.log(person2.getName()); // 'Michael'

</script>
</body>
</html>